package com.newangels.action;

import com.newangels.service.AgentManagerService;
import jade.util.leap.ArrayList;
import jade.wrapper.ControllerException;
import jade.wrapper.gateway.JadeGateway;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import static com.newangels.service.impl.AgentManagerServiceImpl.getAgentManagerServiceImpl;

@WebServlet("/killAllAgents")
public class KillAllAgentsServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(KillAllAgentsServlet.class.getName());
    AgentManagerService agentManagerService = getAgentManagerServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        String AGENT_STATE_ = request.getParameter("AGENT_STATE_");
        String STATE_ = request.getParameter("STATE_");
        //查询 启动状态的智能体
        List<Map<String, Object>> list = agentManagerService.selectAgents(null, null, null, null, null, AGENT_STATE_, STATE_, null, null, -1, -1);
        //关闭 启动状态的智能体
        jade.util.leap.List agentList = new ArrayList();
        for (int i = 0, len = list.size(); i < len; i++) {
            agentList.add(i, list.get(i).get("AGENT_CODE_"));
        }
        try {
            JadeGateway.execute(agentList);
        } catch (ControllerException e) {
            logger.warning(e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            logger.warning(e.getMessage());
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", true);
        response.getWriter().write(jsonObject.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
